package com.g4m.baselib.component;

import com.g4m.baselib.entity.Response;
import com.g4m.baselib.entity.WebConstants;
import com.g4m.baselib.tool.ClientInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created on 2020-01-01
 * <p>Copyright 2008-2020 snsndk.com</p>
 * <p>
 * hudesen[hudesen@hudesen.com]
 */
@Slf4j
@RestController
public class GlobalErrorController implements ErrorController {
    private final static String RESPONSE_FIELD_STATUS = "status";
    private final static String RESPONSE_STATUS_404 = "404";

    @Autowired
    private ErrorAttributes errorAttributes;

    /**
     * 默认错误
     */
    private static final String PATH_DEFAULT = "/error";

    /**
     * 获取错误接口路径
     *
     * @return 字符串
     */
    @Override
    public String getErrorPath() {
        return PATH_DEFAULT;
    }

    /**
     * JSON格式错误信息
     *
     * @param request             请求
     * @param httpServletResponse 返回
     * @return res
     */
    @RequestMapping(value = PATH_DEFAULT, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Response handleError(HttpServletRequest request, HttpServletResponse httpServletResponse) {
        ClientInfo.addCrossDomain(request, httpServletResponse);
        if (this.errorAttributes != null) {
            Map<String, Object> errorBody = this.errorAttributes.getErrorAttributes(new ServletWebRequest(request), true);
            if (errorBody != null && RESPONSE_STATUS_404.equals(errorBody.get(RESPONSE_FIELD_STATUS).toString())) {
                log.debug("requestError:{}", errorBody);
            } else {
                log.error("requestError:{}", errorBody);
            }
        }
        return Response.buildResponse(WebConstants.RESPONSE_RESULT_SYSTEM_ERROR);
    }
}
